from flask import render_template, redirect, url_for, request, flash
from flask import request, jsonify, url_for, redirect
from flask_login import login_user, logout_user, login_required, current_user
from extensions import db, login_manager
from models import User, Employee,Department
from routes import auth_bp
from datetime import datetime
from utils import Result, success, error, bad_request

# 用户加载器
@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))

# 直接使用Flask-JWT-Extended提供的函数
from flask_jwt_extended import create_access_token

# 生成JWT token的函数
def generate_jwt_token(user_id, role):
    """
    生成JWT token
    
    :param user_id: 用户ID
    :param role: 用户角色
    :return: JWT token字符串
    """
    additional_claims = {
        "role": role
    }
    # identity必须是字符串类型
    access_token = create_access_token(identity=str(user_id), additional_claims=additional_claims)
    return access_token

# 登录API
@auth_bp.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        # 检查请求是否为JSON格式
        if request.is_json:
            data = request.get_json()
            username = data.get('username')
            password = data.get('password')
        
        if not username or not password:
            return bad_request('用户名和密码不能为空').to_response()
        
        user = User.query.filter_by(username=username).first()
        if user and user.check_password(password):
            login_user(user)
            
            # 生成JWT token
            token = generate_jwt_token(user.id, user.role)
            
            # 构建返回的信息（除了密码之外的所有字段）
            department_name = None
            if user.department_id:
                dept = Department.query.get(user.department_id)
                department_name = dept.name if dept else None
            
            data = {
                'user_info': {
                    'id': user.id,
                    'username': user.username,
                    'role': user.role,
                    'name': user.name,
                    'gender': user.gender,
                    'birth_date': user.birth_date.isoformat() if user.birth_date else None,
                    'phone': user.phone,
                    'email': user.email,
                    'department_id': user.department_id,
                    'department_name': department_name,
                    'position': user.position,
                    'address': user.address,
                    'avatar': user.avatar
                },
                'token': token
            }
            
            return success(data=data, msg='登录成功').to_response()
        else:
            return error(code=401, msg='用户名或密码错误').to_response()
    
    # GET请求返回登录页面
    return render_template('/login.html')

# 注册API
@auth_bp.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        # 检查请求是否为JSON格式
        if request.is_json:
            data = request.get_json()
            username = data.get('username')
            password = data.get('password')
            confirm_password = data.get('confirm_password')
            role = data.get('role', 'employee')

        # 字段校验
        if User.query.filter_by(username=username).first():
            return error(code=400, msg='账号已存在').to_response()
        if password != confirm_password:
            return error(code=400, msg='两次输入的密码不一致').to_response()
        # 创建新用户
        user = User(username=username, role=role)
        user.set_password(password)
        try:
            db.session.add(user)
            db.session.commit()
            return success(msg='注册成功！请登录').to_response()
        except Exception as e:
            db.session.rollback()
            return error(msg=f'注册失败：{str(e)}').to_response()
    return render_template('/register.html')

# 登出API
@auth_bp.route('/logout')
@login_required
def logout():
    logout_user()
    return success(msg='已成功登出').to_response()

# 修改个人信息API
@auth_bp.route('/profile', methods=['PUT'])
@login_required
def update_profile():
    """修改个人信息"""
    try:
        # 检查请求是否为JSON格式
        if not request.is_json:
            return bad_request('请求必须是JSON格式').to_response()
        
        data = request.get_json()
        user = current_user
        
        # 更新用户信息
        if 'name' in data:
            user.name = data['name']
        if 'gender' in data:
            user.gender = data['gender']
        if 'phone' in data:
            user.phone = data['phone']
        if 'email' in data:
            user.email = data['email']
        if 'position' in data:
            user.position = data['position']
        if 'address' in data:
            user.address = data['address']
        if 'avatar' in data:
            user.avatar = data['avatar']
        
        # 处理出生日期
        if 'birth_date' in data and data['birth_date']:
            try:
                user.birth_date = datetime.strptime(data['birth_date'], '%Y-%m-%d').date()
            except ValueError:
                return bad_request(msg='出生日期格式错误').to_response()
        
        # 处理部门ID
        if 'department_id' in data:
            user.department_id = data['department_id']
        
        # 更新修改时间
        user.updated_at = datetime.utcnow()
        
        db.session.commit()
        
        return success(msg='个人信息修改成功').to_response()
        
    except Exception as e:
        db.session.rollback()
        return error(msg=f'修改个人信息失败: {str(e)}').to_response()

# 修改密码API
@auth_bp.route('/change-password', methods=['POST'])
@login_required
def change_password():
    """修改密码"""
    try:
        # 检查请求是否为JSON格式
        if not request.is_json:
            return bad_request('请求必须是JSON格式').to_response()
        
        data = request.get_json()
        old_password = data.get('old_password')
        new_password = data.get('new_password')
        confirm_password = data.get('confirm_password')
        
        # 验证必填字段
        if not old_password or not new_password or not confirm_password:
            return bad_request(msg='请填写完整信息').to_response()
        
        # 验证新密码两次输入是否一致
        if new_password != confirm_password:
            return bad_request(msg='新密码两次输入不一致').to_response()
        
        # 验证新密码长度
        if len(new_password) < 6:
            return bad_request(msg='新密码长度不能少于6位').to_response()
        
        user = current_user
        
        # 验证旧密码
        if not user.check_password(old_password):
            return error(code=400, msg='原密码错误').to_response()
        
        # 设置新密码
        user.set_password(new_password)
        user.updated_at = datetime.utcnow()
        
        db.session.commit()
        
        return success(msg='密码修改成功').to_response()
        
    except Exception as e:
        db.session.rollback()
        return error(msg=f'修改密码失败: {str(e)}').to_response()
